﻿using Albatross.WPF.Common.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace Albatross.WPF.Common.Views {
	public class SelectionChangedCommand : Behavior<Selector> {
		protected override void OnAttached() {
			base.OnAttached();
			AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
		}

		protected override void OnDetaching() {
			base.OnDetaching();
			AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
		}

		public const string CommandPropertyName = "Command";
		public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(CommandPropertyName, typeof(ICommand), typeof(SelectionChangedCommand), new PropertyMetadata());
		public ICommand Command {
			get { return (ICommand)GetValue(CommandProperty); }
			set { SetValue(CommandProperty, value); }
		}
		
		void AssociatedObject_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) {
			CommandParameter cmdParam = new CommandParameter() {
				Value = AssociatedObject.SelectedItem,
				ViewService = (IViewService)AssociatedObject.GetValue(Attached.ViewServiceProperty),
			};
			if (Command != null && Command.CanExecute(cmdParam)) {
				Command.Execute(cmdParam);
			}
		}
	}
}
